package com.ahua.mallchat.common.service.impl;

import com.ahua.mallchat.common.adapter.WXTextBuilder;
import com.ahua.mallchat.common.adapter.UserAdapter;
import com.ahua.mallchat.common.dao.UserDao;
import com.ahua.mallchat.common.domain.pojo.User;
import com.ahua.mallchat.common.service.UserService;
import com.ahua.mallchat.common.service.WebSocketService;
import com.ahua.mallchat.common.service.WxMsgService;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WxMsgServiceImpl implements WxMsgService {

    private static final String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    /**
     * openId和code的映射关系
     */
    private static final ConcurrentHashMap<String, Integer> WAIT_AUTHORIZATION_MAP = new ConcurrentHashMap<>();

    @Value("${wx.mp.callback}")
    private String callback;

    @Resource
    private UserDao userDao;

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private WebSocketService webSocketService;

    @Override
    public WxMpXmlOutMessage scan(WxMpService wxMpService, WxMpXmlMessage wxMpXmlMessage) {

        String openId = wxMpXmlMessage.getFromUser();
        Integer code = getEventKey(wxMpXmlMessage);

        User user = userDao.getByOpenId(openId);
        if (Objects.nonNull(user) && StringUtils.hasText(user.getAvatar())) {
            //注册过的 且已经授权过的 直接登陆成功
            webSocketService.scanLoginSuccess(code, user.getId());
            return WXTextBuilder.build("登录成功", wxMpXmlMessage);
        }

        //告知前端用户扫描成功等待授权
        webSocketService.waitAuthorize(code);

        WAIT_AUTHORIZATION_MAP.put(openId, code);
        if (Objects.isNull(user)) {
            //user为空 就先去注册一个
            User insert = UserAdapter.buildUserSave(openId);
            userService.register(insert);
        }

        //生成一个授权的链接
        String authorizaUrl = String.format(URL, wxMpService.getWxMpConfigStorage().getAppId(), URLEncoder.encode(callback + "/wx/portal/public/callBack"));

        return WXTextBuilder.build("请点击链接授权：<a href=\"" + authorizaUrl + "\">登录</a>", wxMpXmlMessage);
    }

    @Override
    public void authorize(WxOAuth2UserInfo userInfo) {
        String openid = userInfo.getOpenid();
        User user = userDao.getByOpenId(openid);
        //更新用户信息
        if (!StringUtils.hasText(user.getAvatar())) {
            fillUserInfo(user.getId(), userInfo);
        }
        Integer code = WAIT_AUTHORIZATION_MAP.remove(openid);
        webSocketService.scanLoginSuccess(code, user.getId());
//        webSocketService.authorizationSuccess(, user);
    }

    /**
     * 更新用户数据
     *
     * @param id
     * @param userInfo
     */
    private void fillUserInfo(Long id, WxOAuth2UserInfo userInfo) {
        User user = UserAdapter.buildFillInfoUser(id, userInfo);
        try {
            userDao.updateById(user);
        } catch (DuplicateKeyException e) {
            //唯一键冲突的异常
            //因为name我们不能重复嘛。 所以可以在这里去做个兜底的机制
            //如果name重复了 那就随机生成个 或者干嘛 都可以
        }
    }

    /**
     * 获取登陆码，如果是新关注的用户 它是有可能带有qrscene_前缀的 要先去掉
     *
     * @param wxMpXmlMessage
     * @return
     */
    private Integer getEventKey(WxMpXmlMessage wxMpXmlMessage) {
        String eventKey = wxMpXmlMessage.getEventKey();
        String code = eventKey.replace("qrscene_", "");
        return Integer.parseInt(code);
    }
}
